<template lang="pug">
    .searchInput
        svg.icon.searchIcon(aria-hidden="true")
            use(xlink:href='#icon-search')
        input(type="search",v-model="searchInput",ref="searchInput",@keyup.13="search",placeholder="请输入搜索内容",@focus="focus",@blur="blur")
        svg.icon.cancel(:class="{activeCancel:isActive}",aria-hidden="true",v-if="searchInput",@click="cancel",@touchstart.prevent="cancel")
            use(xlink:href="#icon-close")
</template>

<script type="es6">
	export default {
		name: 'searchInput',
		data () {
			return {
				searchInput: '',
				isActive: false
			}
		},
		props: ['resultMutationName', 'searchUrl', 'searchKeyMutationName', 'searchKeyName', 'pageSize'],
		methods: {
			cancel(ev){
				this.searchInput = ''
				this.$refs.searchInput.focus()
			},
			focus(ev){
				this.isActive = true
			},
			blur(ev){
				this.isActive = false
			},
			search(){
				let pageSize = this.pageSize || 10

				this.$store.commit(this.resultMutationName, this.searchInput)
				this.$http.get(this.searchUrl, {
					params: {
						key: this.$store.state[this.searchKeyName],
						pageSize: pageSize,
						pageNumber: 1
					}
				}).then(response => {
					this.$store.commit(this.resultMutationName, response.data.data.list)
				}).catch(error => {
					console.log(error)
				})
			}
		},
		mounted(){

			this.$refs.searchInput.blur()
			this.searchInput = this.$store.state[this.searchKeyName]
		}
	}
</script>

<style lang="stylus" scoped>
    @import "../../styles/common.styl"
    .activeCancel
        display inline !important

    ::-moz-placeholder
        color: #fff

    ::-webkit-input-placeholder
        color: #fff

    :-ms-input-placeholder
        color: #fff

    input[type="search"]::-webkit-search-cancel-button
        display none

    input[type="search"]
        -webkit-appearance none

    .searchInput
        width 12rem
        margin-left 1rem
        border-bottom 1px solid $assistantColor
        background $mainColor
        overflow hidden
        input
            padding .2rem
            border none
            font-size .65rem
            outline none
            color $assistantColor
            width 10rem
            line-height 1.05rem
            background $mainColor
            &:focus
                color $assistantColor
        .searchIcon
            display block
            float left
            z-index 1000
            color $assistantColor
            margin: .3rem .2rem 0 0
            font-size .9rem
        .cancel
            borderRadius(50%)
            color $mainColor
            background $assistantColor
            font-size .5rem
            padding .1rem
            position absolute
            right 3rem
            margin-top .3rem
            display none
</style>
